import { RootDispatch } from "@src/store";
import Api from "@services/api";

export interface LoginStateDeclaration {
  isLogin: boolean;
  name: string;
  Authorization: string;
  maxFraction: number;
  userId: number | null;
  scoreRecord: any[];
  rank: number;
}
const Authorization = localStorage.getItem("Authorization");

const state: LoginStateDeclaration = {
  isLogin: Authorization != null,
  name: "",
  maxFraction: 0,
  Authorization: Authorization || "",
  userId: null,
  scoreRecord: [],
  rank: 0,
};
export default {
  name: "login",
  state,
  reducers: {
    login: (state: LoginStateDeclaration, payload?: any): LoginStateDeclaration => {
      console.log("redux login");
      const { name, maxFraction, token, id } = payload;
      state.isLogin = true;
      state.name = name;
      state.userId = id;
      state.maxFraction = maxFraction;
      state.Authorization = `Bearer ${token}`;
      localStorage.setItem("Authorization", state.Authorization);
      console.log(state);
      return state;
    },
    logout: (state: LoginStateDeclaration, payload?: any): LoginStateDeclaration => {
      state.isLogin = false;
      state.name = "";
      state.maxFraction = 0;
      state.Authorization = "";
      localStorage.removeItem("Authorization");
      return state;
    },
    setTouristInfo: (state: LoginStateDeclaration, payload?: any): LoginStateDeclaration => {
      const { name, maxFraction, id, scoreRecord = [], rank } = payload;
      state.name = name;
      state.userId = id;
      state.maxFraction = maxFraction;
      state.scoreRecord = scoreRecord;
      state.rank = rank;
      return state;
    },
  },
  // effects 可以是一个函数，也可以是一个对象
  // 还没研究过源码，猜测：是函数时可以派发其他 model 中的 action；是对象时只能派发当前 model 中的 action
  effects: (dispatch: RootDispatch) => ({
    async fetchTouristLogin(payload: { name: string }) {
      const data = await Api.user.touristLogin(payload);
      console.log("fetchTouristLogin", data);
      dispatch.login.login(data);
    },

    async fetchTouristInfo() {
      const data = await Api.user.touristInfo();
      console.log("fetchTouristInfo", data);
      dispatch.login.setTouristInfo(data);
    },
  }),
};
